package com.nowcoder.community.actuator;

import com.nowcoder.community.util.CommunityConstant;
import com.nowcoder.community.util.CommunityUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.endpoint.annotation.Endpoint;
import org.springframework.boot.actuate.endpoint.annotation.ReadOperation;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * @ClassName DatabaseEndpoint
 * @Description
 * @Author hhwu
 * @Date 2022/6/3 22:22
 * Version 1.0
 **/
@Component
@Endpoint(id = "database")// 端点的访问路径
public class DatabaseEndpoint {
    /**
     * @Author hhwu
     * @Description //TODO 自定义监控端点
     * @Date 22:23 2022/6/3
     **/

    private static final Logger logger = LoggerFactory.getLogger(DatabaseEndpoint.class);
    
    @Autowired
    private DataSource dataSource;
    
    @ReadOperation// get请求
    public String checkConnection() {
        /**
         * @Author hhwu
         * @Description //TODO 测试数据库是否能联通
         * @Date 22:30 2022/6/3
         * @Param []
         * @return java.lang.String
         **/
        try (

                Connection connection = dataSource.getConnection();
                ){
            return CommunityUtil.getJSONString(0, "获取连接成功！");
        } catch (SQLException e) {
            logger.error("获取连接失败：" + e.getMessage());
            return CommunityUtil.getJSONString(0, "获取连接失败!");
        }
    }
}
